/**
 * Created by MyPC on 2017/6/12.
 */
let mysql = require('../../common/mysql');
let dao = {};

dao.listByPage = function (page) {
  let sql = 'SELECT id,`names`,is_multi as isMulti,update_time updateTime,remarks,operator_id as operatorId FROM `t_c_parts_group` WHERE delete_time IS NULL ';
  let arr = [];
  if (page.query.names) {
    sql += ' and names=? ';
    arr.push(page.query.names);
  }
  if (page.query.isMulti) {
    sql += ' and is_multi=? ';
    arr.push(page.query.isMulti);
  }
  sql += 'ORDER BY id DESC LIMIT ' + (page.pageNum - 1) * page.pageSize + ',' + page.pageSize;
  return new Promise(function (resolve, reject) {
    mysql.query(sql, arr, function (error, results, fields) {
      if (error) reject(error);
      resolve(results, fields);
    })
  });
}
dao.countByPage = function (page) {
  let sql = 'SELECT count(id) as total FROM `t_c_parts_group` WHERE delete_time IS NULL ';
  let arr = [];
  if (page.query.names) {
    sql += ' and names=? ';
    arr.push(page.query.names);
  }
  if (page.query.isMulti) {
    sql += ' and is_multi=? ';
    arr.push(page.query.isMulti);
  }
  return new Promise(function (resolve, reject) {
    mysql.query(sql, arr, function (error, results, fields) {
      if (error) reject(error);
      resolve(results, fields);
    })
  });
}
dao.save = function (params) {
  let sql = 'insert into t_c_parts_group(names,is_multi,remarks) value (?,?,?)';
  let arr = [];
  arr.push(params.names);
  arr.push(params.isMulti);
  arr.push(params.remarks);
  return new Promise(function (resolve, reject) {
    mysql.query(sql, arr, function (error, results, fields) {
      if (error) reject(error);
      resolve(results, fields);
    })
  })
}
dao.removeById = function (id) {
  return new Promise(function (resolve, reject) {
    mysql.query('update t_c_parts_group set delete_time=now() where delete_time is null and id=? ', [id], function (error, results, fields) {
      if (error) reject(error);
      resolve(results, fields);
    });
  })
}
dao.updateById = function (params) {
  let sql = 'update t_c_parts_group set names=?,is_multi=?,remarks=?,update_time=now() where id=?';
  let arr = [];
  arr.push(params.names);
  arr.push(params.isMulti);
  arr.push(params.remarks);
  arr.push(params.id);
  return new Promise(function (resolve, reject) {
    mysql.query(sql, arr, function (error, results, fields) {
      if (error) reject(error);
      resolve(results, fields);
    })
  })
}

module.exports = dao;

